package com.the9tcat.funnyalarmclock.oauth;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;


public class OauthRequest {
	private String httpMethod = "";

	private String requestUrl = "";

	List<OauthParams> params = new ArrayList<OauthParams>();

	public OauthRequest(String url, String method, List<OauthParams> params) {
		requestUrl = url;
		httpMethod = method;
		Collections.sort(params, new OauthParamsComparator());
		this.params = params;
	}

	/** 由给定的签名参数，用GET方法返回结果 */
	public String resultByGET(String signKey) {
        StringBuffer sb = new StringBuffer(requestUrl);
        sb.append("?");
        for(int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).key);
            sb.append("=");
            sb.append(params.get(i).value);
            sb.append("&");
        }
        sb.append("oauth_signature=");
        sb.append(OauthSignature.normalUrlEncode(OauthSignature.sign(getBaseString(), signKey)));
	    return OauthHttp.stringByGet(sb.toString());
	}
	
	/** 由给定的签名参数，用POST方法返回结果 */
	public String resultByPOST(String signKey) {
		List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
		for(int i = 0; i < params.size(); i++) {
            postData.add(new BasicNameValuePair(params.get(i).key, params.get(i).value));
        }
		postData.add(new BasicNameValuePair("oauth_signature", (OauthSignature
				.sign(getBaseString(), signKey))));
		return OauthHttp.stringByPOST(requestUrl, postData);
	}

	/** 返回基本字串 */
	private String getBaseString() {
		if (httpMethod == "") {
			throw new OauthException("Http Method Can Not Be Blank!");
		}
		if (requestUrl == "") {
			throw new OauthException("Request Url Can Not Be Blank!");
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append(httpMethod);
		sb.append("&");
		sb.append(URLEncoder.encode(requestUrl));
		sb.append("&");
		for(int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).key);
			sb.append("%3D");
			sb.append(OauthSignature.oauthUrlEncode(params.get(i).value));
			if (i != params.size() - 1) {
				sb.append("%26");
			}
		}

		return sb.toString();
	}
}
